<template>
  <div class="chat">
    <div :class="['tui-chat', !isPC && 'tui-chat-h5']">
      <div v-if="!currentConversationID" :class="['tui-chat-default', !isPC && 'tui-chat-h5-default']">
        <slot />
      </div>
      <div v-if="currentConversationID" :class="['tui-chat', !isPC && 'tui-chat-h5']">
        <ChatHeader :class="[
            'tui-chat-header',
            !isPC && 'tui-chat-H5-header',
            isUniFrameWork && 'tui-chat-uniapp-header',
          ]" :groupInfo="groupInfo" @closeChat="closeChat" :isNotInGroup="isNotInGroup" />
        <Forward @toggleMultipleSelectMode="toggleMultipleSelectMode" />
        <MessageList ref="messageListRef" :class="['tui-chat-message-list', !isPC && 'tui-chat-h5-message-list']"
          :isGroup="isGroup" :groupID="groupID" :isNotInGroup="isNotInGroup"
          :isMultipleSelectMode="isMultipleSelectMode" @handleEditor="handleEditor"
          @closeInputToolBar="() => changeToolbarDisplayType('none')"
          @toggleMultipleSelectMode="toggleMultipleSelectMode" />
        <div v-if="isNotInGroup" :class="{
            'tui-chat-leave-group': true,
            'tui-chat-leave-group-mobile': isMobile,
          }">
          {{ leaveGroupReasonText }}
        </div>
        <MultipleSelectPanel v-else-if="isMultipleSelectMode" @oneByOneForwardMessage="oneByOneForwardMessage"
          @mergeForwardMessage="mergeForwardMessage" @toggleMultipleSelectMode="toggleMultipleSelectMode"
          @selectMessage="selectMessage" />
        <template v-else>
          <MessageInputToolbar v-if="isInputToolbarShow" :class="[
              'tui-chat-message-input-toolbar',
              !isPC && 'tui-chat-h5-message-input-toolbar',
              isUniFrameWork && 'tui-chat-uni-message-input-toolbar'
            ]" :displayType="inputToolbarDisplayType" @insertEmoji="insertEmoji"
            @changeToolbarDisplayType="changeToolbarDisplayType" @scrollToLatestMessage="scrollToLatestMessage"
            :groupInfo="groupInfo" />
          <MessageInput ref="messageInputRef" :class="[
              'tui-chat-message-input',
              !isPC && 'tui-chat-h5-message-input',
              isUniFrameWork && 'tui-chat-uni-message-input',
              isWeChat && 'tui-chat-wx-message-input',
            ]" :enableAt="featureConfig.InputMention" :isMuted="false"
            :muteText="TUITranslateService.t('TUIChat.您已被管理员禁言')" :placeholder="TUITranslateService.t('TUIChat.请输入消息')"
            :inputToolbarDisplayType="inputToolbarDisplayType" @changeToolbarDisplayType="changeToolbarDisplayType" />
        </template>
      </div>
      <!-- Group Management -->
      <div v-if="!isNotInGroup && isUniFrameWork && isGroup && headerExtensionList.length > 0" class="group-profile"
        @click="handleGroup">
        {{ headerExtensionList[0].text }}
      </div>

      <div v-if="workOrderDrefList.length > 0 && !sidebarStore.isOpen && !isNotInGroup">
        <el-popover placement="left" :width="530" :visible="showDraft">
          <template #default>
            <div style="width: 100%; height: 20px">
              <el-icon :size="20" style="float: right; cursor: pointer;" @click="showDraft = false">
                <Close />
              </el-icon>
            </div>
            <el-table :data="workOrderDrefList" style="width: 100%" align="center">
              <el-table-column prop="title" label="工单名称" width="110" />
              <el-table-column prop="name" label="上次操作时间" width="170" align="center">
                <template #default="scope">
                  <span>{{ scope.row.update_time ? scope.row.update_time : scope.row.create_time }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="creator_name" label="创建人" width="100" align="center" />
              <el-table-column label="操作" width="120" align="center">
                <template #default="scope">
                  <el-button type='primary' text style="width: 30px; padding: 0; display: inline-block;"
                    @click="openDetail(scope.row)">编辑</el-button>
                  <el-button type='danger' text style="width: 30px; padding: 0; display: inline-block;"
                    @click="del(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
          <template #reference>
            <div class="work-order-draft">
              <div style="position: relative;" @click="handleShowDraft">
                <el-badge :value="workOrderDrefList.length">
                  <img src="../../assets/icon/work-order.png">
                </el-badge>
              </div>
            </div>
          </template>
        </el-popover>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { delWorkOrderDraft, getGroupInfo, getWorkOrderDraft } from '@/api';
import { useMulitpleSelectStore } from '@/store/mulitpleSelect';
import { useSidebarStore } from '@/store/sidebar';
import TUIChatEngine, {
  IConversationModel,
  IMessageModel,
  StoreName,
  TUIConversationService,
  TUIStore,
  TUITranslateService,
} from '@tencentcloud/chat-uikit-engine';
import TUICore, { ExtensionInfo, TUIConstants } from '@tencentcloud/tui-core';
import { computed, onMounted, onUnmounted, ref } from '../../adapter-vue';
import { ToolbarDisplayType } from '../../interface';
import { isMobile, isPC, isUniFrameWork, isWeChat } from '../../utils/env';
import ChatHeader from './chat-header/index.vue';
import TUIChatConfig from './config';
import Forward from './forward/index.vue';
import MessageInputToolbar from './message-input-toolbar/index.vue';
import MessageInput from './message-input/index.vue';
import MessageList from './message-list/index.vue';
import MultipleSelectPanel from './mulitple-select-panel/index.vue';

const emits = defineEmits(['closeChat']);

const groupID = ref(undefined);
const isGroup = ref(false);
const isNotInGroup = ref(false);
const notInGroupReason = ref<number>();
const currentConversationID = ref();
const isMultipleSelectMode = ref(false);
const inputToolbarDisplayType = ref<ToolbarDisplayType>('none');
const messageInputRef = ref();
const messageListRef = ref<InstanceType<typeof MessageList>>();
const headerExtensionList = ref<ExtensionInfo[]>([]);
const featureConfig = TUIChatConfig.getFeatureConfig();
const groupInfo = ref('');
const sidebarStore = useSidebarStore();
const mulitpleSelectStore = useMulitpleSelectStore();
const workOrderDrefList = ref([]);
const showDraft = ref(false);

onMounted(() => {
  TUIStore.watch(StoreName.CONV, {
    currentConversationID: onCurrentConversationIDUpdate,
    currentConversation: onCurrentConversationUpdate,
  });
});

onUnmounted(() => {
  TUIStore.unwatch(StoreName.CONV, {
    currentConversationID: onCurrentConversationIDUpdate,
    currentConversation: onCurrentConversationUpdate,
  });
  reset();
});

sidebarStore.$subscribe((mutate, state) => {
  if (!state.isOpen) {
    if (state.type == 'workOrder') {
      // getDraftList(groupInfo.value.GroupId)
    }
  }
})

mulitpleSelectStore.$subscribe((mutate, state) => {
  toggleMultipleSelectMode(state.isOpen);
})


const isInputToolbarShow = computed<boolean>(() => {
  return isUniFrameWork ? inputToolbarDisplayType.value !== 'none' : true;
});

const leaveGroupReasonText = computed<string>(() => {
  let text = '';
  switch (notInGroupReason.value) {
    case 4:
      text = TUITranslateService.t('TUIChat.您已被管理员移出群聊');
      break;
    case 5:
      text = TUITranslateService.t('TUIChat.该群聊已被解散');
      break;
    case 8:
      text = TUITranslateService.t('TUIChat.您已退出该群聊');
      break;
    default:
      text = TUITranslateService.t('TUIChat.您已退出该群聊');
      break;
  }
  return text;
});

const reset = () => {
  TUIConversationService.switchConversation('');
};

const closeChat = (conversationID: string) => {
  emits('closeChat', conversationID);
  reset();
};

const insertEmoji = (emojiObj: object) => {
  messageInputRef.value?.insertEmoji(emojiObj);
};

const handleEditor = (message: IMessageModel, type: string) => {
  if (!message || !type) return;
  switch (type) {
    case 'reference':
      // todo
      break;
    case 'reply':
      // todo
      break;
    case 'reedit':
      if (message?.payload?.text) {
        messageInputRef?.value?.reEdit(message?.payload?.text);
      }
      break;
    default:
      break;
  }
};

const handleGroup = () => {
  headerExtensionList.value[0].listener.onClicked({ groupID: groupID.value });
};

function changeToolbarDisplayType(type: ToolbarDisplayType) {
  inputToolbarDisplayType.value = inputToolbarDisplayType.value === type ? 'none' : type;
  if (inputToolbarDisplayType.value !== 'none' && isUniFrameWork) {
    uni.$emit('scroll-to-bottom');
  }
}

function scrollToLatestMessage() {
  messageListRef.value?.scrollToLatestMessage();
}

function toggleMultipleSelectMode(visible?: boolean) {
  isMultipleSelectMode.value = visible === undefined ? !isMultipleSelectMode.value : visible;
}

function mergeForwardMessage() {
  messageListRef.value?.mergeForwardMessage();
}

function oneByOneForwardMessage() {
  messageListRef.value?.oneByOneForwardMessage();
}

function selectMessage() {
  messageListRef.value?.selectMessage();
}

function getInfo() {
  getGroupInfo({
    GroupId: groupID.value,
  }).then((res: any) => {
    let result = res.data;
    groupInfo.value = result;
    sidebarStore.setSidebar({
      isOpen: sidebarStore.isOpen,
      groupInfo: result,
      type: sidebarStore.type,
      currentId: '',
    });
    // getDraftList(result.GroupId)
  }).catch((err: any) => {

  })
}

function getDraftList(groupID: string){
  getWorkOrderDraft({
    group_id: groupID
  }).then(res => {
    workOrderDrefList.value = res.data
    if (res.data.length == 0) {
      showDraft.value = false;
    }
  })
}

function openDetail(e: any){
  showDraft.value = false;
  sidebarStore.setSidebar({
    isOpen: true,
    groupInfo: sidebarStore.groupInfo,
    type: 'workOrder',
    currentId: e.id,
  });
}

function del(e: any){
  delWorkOrderDraft({
    id: e.id
  }).then(res => {
    getDraftList(groupInfo.value.GroupId)
  })
}

function handleShowDraft(){
  showDraft.value = !showDraft.value
}

function onCurrentConversationUpdate(conversation: IConversationModel) {
  if (conversation?.operationType > 0) {
    headerExtensionList.value = [];
    isNotInGroup.value = true;
    /**
     * 4 - be removed from the group
     * 5 - group is dismissed
     * 8 - quit group
     */
    notInGroupReason.value = conversation?.operationType;
  } else {
    isNotInGroup.value = false;
    notInGroupReason.value = undefined;
  }
}

function onCurrentConversationIDUpdate(conversationID: string) {
  if (currentConversationID.value === conversationID) {
    return;
  }
  sidebarStore.setSidebar({
    isOpen: false,
    groupInfo: sidebarStore.groupInfo,
    type: sidebarStore.type,
    currentId: '',
  });
  isGroup.value = false;
  let conversationType = TUIChatEngine.TYPES.CONV_C2C;
  if (conversationID.startsWith(TUIChatEngine.TYPES.CONV_GROUP)) {
    conversationType = TUIChatEngine.TYPES.CONV_GROUP;
    isGroup.value = true;
    groupID.value = conversationID.replace(TUIChatEngine.TYPES.CONV_GROUP, '');
    getInfo();
  }
  headerExtensionList.value = [];
  currentConversationID.value = conversationID;
  isMultipleSelectMode.value = false;
  // Initialize chatType
  TUIChatConfig.setChatType(conversationType);
  // While converstaion change success, notify callkit and roomkit、or other components.
  TUICore.notifyEvent(TUIConstants.TUIChat.EVENT.CHAT_STATE_CHANGED, TUIConstants.TUIChat.EVENT_SUB_KEY.CHAT_OPENED, { groupID: groupID.value });
  // The TUICustomerServicePlugin plugin determines if the current conversation is a customer service conversation, then sets chatType and activates the conversation.
  TUICore.callService({
    serviceName: TUIConstants.TUICustomerServicePlugin.SERVICE.NAME,
    method: TUIConstants.TUICustomerServicePlugin.SERVICE.METHOD.ACTIVE_CONVERSATION,
    params: { conversationID: conversationID },
  });
  // Get chat header extensions
  if (TUIChatConfig.getChatType() === TUIConstants.TUIChat.TYPE.GROUP) {
    headerExtensionList.value = TUICore.getExtensionList(TUIConstants.TUIChat.EXTENSION.CHAT_HEADER.EXT_ID);
  }
}
</script>

<style scoped lang="scss" src="./style/index.scss"></style>
<style lang="scss" scoped>
  .work-order-draft{
    width: 50px;
    height: 50px;
    position: fixed;
    right: 40px;
    top: 30%;
    cursor: pointer;

    img{
      width: 50px;
      height: 50px;
    }
  }
</style>
